<template>
    <div  :class="['wbs-gantt-container', $route.query.projectId ? 'full-screen' : '']">
      <el-row>
        <el-col :span="24">
          <span class="select-label">时间轴：</span>
          <el-select v-model="scalesType" placeholder="请选择" style="width: 100px">
            <el-option v-for="item in codeModel.ganttScalesTypeList" :key="item.id" :label="item.name" :value="item.code"></el-option>
          </el-select>
          <span class="select-label">显示列：</span>
          <el-select
            class="cus-col"
            v-model="showFields"
            multiple
            collapse-tags
            @visible-change="visibleChange"
            @remove-tag="removeTag"
            placeholder="请选择">
            <el-option
              v-for="item in showFieldOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary" @click="unfold">
            <template v-if="isFold">全部展开</template>
            <template v-else>全部折叠</template>
          </el-button>
          <slot  name="rightbtn"></slot>
          <el-button type="primary" icon="el-icon-full-screen" @click="openFullScreenPage" class="fullscreen-btn" v-if="!$route.query.projectId">全屏查看</el-button>
          <el-date-picker
            v-model="dragMarkerDate"
            type="date"
            value-format="yyyy-MM-dd 12:00:00"
            placeholder="选择日期"
            :clearable="false"
            @change="changeDragDate"
            style="width: 150px;margin-right: 10px"
            class="fullscreen-btn"
          >
          </el-date-picker>
        </el-col>
      </el-row>
      <gantt-comp class="wbs-gantt" :ref="ganttRefId" :height="ganttHeight" :ganttName="ganttRefId" :taskData="tasks" :scalesType="scalesType" @refreshDragDate="refreshDate" :isShowDragMarker="true" :isOpenTooltip="true" @refreshFold="refreshFold" :showFields="[...showFields, ...fixedFields]"></gantt-comp>
    </div>
</template>

<script>
  /** 子组件 */
  import GanttComp from '../../components/Gantt/Gantt'
  /** 工具 */
  import { getAction } from '@tapui/utils/http'

  export default {
    name: 'WBSGantt',
    components: { GanttComp },
    props: {
      projectId: {
        type: [String, Number],
        default: 0
      },
      ganttRefId: {
        default: 'gantt'
      },
      subtractionHeight: {
        default: 0
      }
    },
    data() {
      return {
        url: {
          getGanttInfo: '/cbb/pmTask/ganttInfo'
        },
        tasks: {
          data: [],
          links: []
        },
        codeModel: {
          ganttScalesTypeList: [
            { code: "day", name: "按日" },
            { code: "week", name: "按周" },
            { code: "month", name: "按月" },
            { code: "year", name: "按年" }
          ]
        },
        scalesType: undefined,
        ganttHeight: '',
        dragMarkerDate: '',
        fixedFields: ['text', 'more'],
        showFields: ['start_date', 'end_date'],
        showFieldOptions: [
          {
            value: 'start_date',
            label: '开始时间',
            change: true
          }, {
            value: 'end_date',
            label: '结束时间',
            change: true
          }
        ],
        isFold: true,
        pickerOptions: {
          disabledDate: (time) => {
            return this.dealDisabledDate(time)
          }
        }
      }
    },
    computed: {
      // 项目id，由父组件或路由传递
      qry_projectId() {
        return this.projectId || this.$route.query.projectId
      }
    },
    methods: {
      visibleChange(display) {
        if (!display) {
          this.$refs[this.ganttRefId].initColumns()
          this.$refs[this.ganttRefId].drawerGantt()
        }
      },
      removeTag(value) {
        this.$nextTick(() => {
          this.$refs[this.ganttRefId].initColumns()
          this.$refs[this.ganttRefId].drawerGantt()
        })
      },
      dealDisabledDate(time) {
        if (this.tasks.data.length > 0) {
          return time.getTime() < this.tasks.data[0].start_date || time.getTime() >= this.tasks.data[0].end_date
        } else {
          return true
        }
      },
      /** 初始化 */
      assignDefaultValue() {
        this.scalesType = 'day'
      },
      /** 查询甘特图数据 */
      getGanttData() {
        this.tasks = {}
        getAction(this.url.getGanttInfo, { projectId: this.qry_projectId }).then((res) => {
          if (res.success) {
            this.tasks.data = res.result.taskList
            this.tasks.links = res.result.lineList
            // 设置默认时间
            let markDate = new Date()
            if (this.tasks.data.length > 0) {
              const maxDate = this.tasks.data.reduce((max, date) => {
                const currentDate = new Date(date.plan_end_date)
                return currentDate > max ? currentDate : max
              }, new Date('1900-01-01'))
              if (markDate > maxDate) {
                markDate = maxDate
              }
              markDate = markDate.toISOString().substr(0, 10) + " 12:00:00"
              markDate = new Date(Date.parse(markDate))
            }
            this.$refs[this.ganttRefId].dragMarkerDate = markDate
            this.dragMarkerDate = markDate
            this.$nextTick(() => {
              this.$refs[this.ganttRefId].drawerGantt()
              this.$nextTick(() => {
                this.isFold = false
                this.unfold()
              })
            })
          } else {
            this.$tap.message(res.message, 'warning')
          }
        })
      },
      /** 计算高度 */
      chargeHeight() {
        if (this.$route.query.projectId) {
          this.ganttHeight = document.body.getBoundingClientRect().height - 70 + 'px'
        } else {
          this.ganttHeight = document.body.getBoundingClientRect().height - 190 - this.subtractionHeight + 'px'
        }
      },
      /** 打开全屏查看页面 */
      openFullScreenPage() {
        let { href } = this.$router.resolve({
          path: '/progressGanttFullScreen',
          query: {
            projectId: this.projectId
          }
        })
        if (this.$store.getters.inMicro) {
          const appName = this.$store.getters.microAppName
          let urlFix = this.$store.getters.microAppList.find((v) => v.name === appName).entry
          if (urlFix.endsWith('/')) {
            urlFix = urlFix.substring(0, urlFix.length - 1)
          }
          href = urlFix + href.substring(appName.length + 1)
        }
        window.open(href, this.$store.getters.token)
      },
      refreshDate(date) {
        this.dragMarkerDate = date
      },
      changeDragDate(date) {
        let dateObj = new Date(date)
        this.$refs[this.ganttRefId].dragMarkerDate = dateObj
        this.$refs[this.ganttRefId].setDragPositionByDate()
      },
      unfold() {
        this.$refs[this.ganttRefId].unfold()
      },
      refreshFold(value) {
        this.isFold = value
      }
    },
    created() {
      // 携带token
      if (this.$route.query.projectId) {
        this.$store.dispatch('Token', window.name)
      }
    },
    mounted() {
      this.assignDefaultValue()
      this.chargeHeight()
      this.getGanttData()
      // 添加高度监听事件
      window.addEventListener('resize', this.chargeHeight)
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', this.chargeHeight)
      })
    }
  }
</script>

<style lang="scss" scoped>
  .full-screen {
    padding: 16px 0 0 12px;
  }
  .wbs-gantt-container {
    /*padding: 16px 0 0 12px;*/

    .select-label {
      color: #606266;
    }

    select-label2 {
      color: #606266;
      margin-right: 10px !important;
    }

    .status-square {
      height: 20px;
      width: 30px;
    }

    .wbs-gantt {
      margin: 10px 12px 12px 0;
    }

    .legend-area {
      float: right;
      margin-top: 5px;
    }

    .fullscreen-btn {
      float: right;
    }
  }

  .scales-type /deep/ .el-input {
    width: 100px !important;
  }

  .cus-col /deep/ .el-input {
    width: 150px !important;
  }
 .no-edge-distance {
   padding: 0;
 }
</style>
